import logging
from logging.handlers import RotatingFileHandler

import redis
from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_wtf.csrf import generate_csrf

from config import DevelopmentConfig, config_map

db = SQLAlchemy()
redis_store = None


def create_app(config_name):
    setup_log(config_name)
    app = Flask(__name__)
    app.config.from_object(config_map.get(config_name))
    db.init_app(app)
    # store_redis = redis.StrictRedis(host=DevelopmentConfig.REDIS_HOST, port=DevelopmentConfig.REDIS_PORT)
    global redis_store
    redis_store = redis.StrictRedis(host=DevelopmentConfig.REDIS_HOST, port=DevelopmentConfig.REDIS_PORT)
    CSRFProtect(app)
    Session(app)

    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class, 'indexClass')

    from info.utils.common import is_deleted
    app.add_template_filter(is_deleted, 'isDeleted')

    from info.utils.common import user_deleted
    app.add_template_filter(user_deleted, 'authorFilter')

    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过 cookie 将值传给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

    from info.utils.common import user_login_data

    @app.errorhandler(404)
    @user_login_data
    def page_not_found(_):
        from flask import g
        from flask import render_template
        return render_template('news/404.html', data={"user_info": g.user.to_dict() if g.user else None})

    from info.index import index_blue
    app.register_blueprint(index_blue)

    from info.passport import passport_blue
    app.register_blueprint(passport_blue)

    from info.news import news_blue
    app.register_blueprint(news_blue)

    from info.profile import profile_blue
    app.register_blueprint(profile_blue)

    from info.admin import admin_blue
    app.register_blueprint(admin_blue)

    from info.other import other_blue
    app.register_blueprint(other_blue)

    return app


def setup_log(config_name):
    logging.basicConfig(level=config_map[config_name].LOG_LEVEL)
    file_log_handler = RotatingFileHandler('logs/log', maxBytes=1024 * 1024 * 100, backupCount=10)
    formatter = logging.Formatter('%(levelname)s %(filename)s: %(lineno)d %(message)s')
    file_log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_log_handler)
